package cn.nexttec.noteplayer.common

import android.Manifest
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.Settings
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat

class PermissionHelper {

    interface PermissionCallback {
        fun onGranted()
        fun onDenied()
    }

    companion object {
        const val REQUEST_CODE_STORAGE = 1001
        const val REQUEST_CODE_MANAGE_ALL_FILES = 1002
        const val REQUEST_CODE_CAMERA = 1003
        private var callback: PermissionCallback? = null

        fun hasPermission(activity: Activity, permission: String): Boolean {
            return ContextCompat.checkSelfPermission(
                activity,
                permission
            ) == PackageManager.PERMISSION_GRANTED
        }

        fun isPermissionGranted(activity: Activity): Boolean {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                // Android 11 及以上，检查是否有“管理所有文件”权限
                Environment.isExternalStorageManager()
            } else {
                ContextCompat.checkSelfPermission(
                    activity,
                    Manifest.permission.READ_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            }
        }

        fun requestStoragePermission(activity: Activity, permissionCallback: PermissionCallback) {
            if (isPermissionGranted(activity)) {
                permissionCallback.onGranted()
            } else {
                callback = permissionCallback
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    try {
                        val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION)
                        intent.data = Uri.parse("package:" + activity.packageName)
                        activity.startActivityForResult(intent, REQUEST_CODE_MANAGE_ALL_FILES)
                    } catch (e: ActivityNotFoundException) {
                        // 如果设备不支持特定设置页，跳通用页
                        val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)
                        activity.startActivityForResult(intent, REQUEST_CODE_MANAGE_ALL_FILES)
                    }
                } else {
                    ActivityCompat.requestPermissions(
                        activity,
                        arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                        REQUEST_CODE_STORAGE
                    )
                }
            }
        }

        fun requestCameraPermission(activity: Activity, permissionCallback: PermissionCallback) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED
            ) {
                permissionCallback.onGranted()
            } else {
                callback = permissionCallback
                ActivityCompat.requestPermissions(
                    activity,
                    arrayOf(Manifest.permission.CAMERA),
                    REQUEST_CODE_CAMERA
                )
            }
        }


        fun onRequestPermissionsResult(
            requestCode: Int,
            permissions: Array<out String>,
            grantResults: IntArray
        ) {
            when (requestCode) {
                REQUEST_CODE_STORAGE, REQUEST_CODE_CAMERA -> {
                    if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        callback?.onGranted()
                    } else {
                        callback?.onDenied()
                    }
                    callback = null
                }
            }

        }

        fun onActivityResult(requestCode: Int, activity: Activity) {
            if (requestCode == REQUEST_CODE_MANAGE_ALL_FILES) {
                if (isPermissionGranted(activity)) {
                    callback?.onGranted()
                } else {
                    callback?.onDenied()
                }
                callback = null
            }
        }
    }
}
